/**
 *  全局页面初始化
 */

function wxRequest(method, url, param, successCallBack, CallBackError, completeCallBack) {
  wx.request({
    url: url,
    method: method,
    data: param,
    header: {
      'X_ManuName': getApp().globalData.manuName
    },
    success: function(res) {
      if (res.statusCode == 200) {
        var data = res.data;
        successCallBack(data)

      }
    },
    fail: function(res) {
      if (typeof CallBackError == "function") {
        CallBackError(res.data)
      }
    },
    complete: function(res) {
      if (typeof completeCallBack == "function") {
        completeCallBack(res.data);
      }
    }
  })
}



/**
 * 微信navigateTo
 */
function navigateTo(url) {
  var index = url.indexOf("?");
  var param = "";
  if (index > -1) {
    param = url.substring(index);
    url = url.substring(0, index);
  }
  GetCustomizView(url, function(data) {
    if (data.code == 1200 && data.content && data.content.View) {
      wx.navigateTo({
        url: data.content.View + param,
      })
      return;
    }
    wx.navigateTo({
      url: url + param
    })
  }, function(data) {
    wx.navigateTo({
      url: url + param
    })
  })
}

/**
 * 微信redirectTo
 */
function redirectTo(url) {
  var index = url.indexOf("?");
  var param = "";
  if (index > -1) {
    param = url.substring(index);
    url = url.substring(0, index);
  }
  GetCustomizView(url, function(data) {
    if (data.code == 1200 && data.content && data.content.View) {
      wx.redirectTo({
        url: data.content.View + param,
      })
      return;
    }
    wx.redirectTo({
      url: url + param
    })
  }, function(data) {
    wx.redirectTo({
      url: url + param
    })
  })
}

/**
 * 微信switchTab
 */
function switchTab(url) {
  var index = url.indexOf("?");
  var param = "";
  if (index > -1) {
    param = url.substring(index);
    url = url.substring(0, index);
  }
  GetCustomizView(url, function(data) {
    if (data.code == 1200 && data.content && data.content.View) {
      wx.switchTab({
        url: data.content.View + param,
      })
      return;
    }
    wx.switchTab({
      url: url + param
    })
  }, function(data) {
    wx.switchTab({
      url: url + param
    })
  })
}

function GetCustomizView(mapUrl, successCallBack, CallBackError) {
  var globalData = getApp().globalData;
  var manuName = globalData.manuName; //厂家名
  wxRequest("get", globalData.apiurl + "/member/api/Customized/GetCustomizView", {
    manuName: manuName,
    map: mapUrl
  }, successCallBack, CallBackError);
}


function pageInit(CallBack) {
  GetLoginSetting(function() {
    //在执行逻辑之前需要执行登陆设置
    const app = getApp();
    var options = getParam();

    var scene = decodeURIComponent(options.scene);
    if (scene.indexOf("UserID") > -1) {
      scene = scene.replace("UserID", "");
    } else {
      scene = null;
    }
    var isTrue = true;
    //执行登陆注册设置逻辑
    isTrue = GetAuthorLoginPage();
    if (isTrue) {
      GetLoginBindPhone();
    }
    var loginSetInfo = wx.getStorageSync("LoginSet");
    if (wx.getStorageSync('UserInfo')) {
      if (wx.getStorageSync("IsBindMobile")) {
        // wx.redirectTo({
        //   url: '/pages/register/register?pageUrl=' + encodeURIComponent(getCurrentPageUrlWithArgs()),
        // })
      } else if (scene) //请求api里面有没有上下级关系吧
      {
        wx.request({
          url: app.globalData.apiurl + '/member/api/Register/UpdateUserRelation',
          method: 'get',
          header: {
            'X_ManuName': app.globalData.manuName
          },
          data: {
            CustId: app.globalData.custID,
            recommendID: scene,
            userId: wx.getStorageSync('UserInfo').UserID
          },
          success: res => {
            var data = res.data;
            if (data.code == 1200 && data.content) {

            }
          },
          complete: res => {

            CallBack();
          }
        });

      } else {
        CallBack();
      }

    } else if (!loginSetInfo || (loginSetInfo && loginSetInfo.IsFollowTis == 1)) {
      wx.redirectTo({
        url: '/pages/sign/sign?parentId=' + scene + '&pageUrl=' + encodeURIComponent(getCurrentPageUrlWithArgs())
      })
    } else {
      CallBack();
    }
  });
}
/*获取当前页带参数的url*/
function getCurrentPageUrlWithArgs() {
  var pages = getCurrentPages() //获取加载的页面
  var currentPage = pages[pages.length - 1] //获取当前页面的对象
  var url = "/" + currentPage.route //当前页面url
  var options = currentPage.options //如果要获取url中所带的参数可以查看options
  //拼接url的参数
  var urlWithArgs = url + '?'
  for (var key in options) {
    if (key != "scene") {
      var value = options[key]
      urlWithArgs += key + '=' + value + '&'
    }
  }
  urlWithArgs = urlWithArgs.substring(0, urlWithArgs.length - 1)
  return urlWithArgs
}

/**
 * 获取当前页面参数
 */
function getParam() {
  var pages = getCurrentPages() //获取加载的页面
  var currentPage = pages[pages.length - 1] //获取当前页面的对象
  var url = currentPage.route //当前页面url
  var options = currentPage.options //如果要获取url中所带的参数可以查看options
  return options;
}
/**
 * 获取登录设置信息
 */
function GetLoginSetting(cb) {
  //if (!wx.getStorageSync("LoginSet")) {
  wx.removeStorageSync("LoginSet")
  const app = getApp();
  wx.request({
    url: app.globalData.apiurl + '/member/api/login/GetLoginSetting',
    method: 'get',
    header: {
      'X_ManuName': app.globalData.manuName
    },
    data: {
      custID: app.globalData.custID,
      terminal: 2,
    },
    success: res => {
      var data = res.data;
      if (data.code == 1200) {

        wx.setStorageSync("LoginSet", res.data.content);
      }
      cb();
    },
    fail: res => {
      cb();
    }
  });
  // } else {
  //   cb();
  // }
}
/**
 *判断是否有启动登陆页
 */
function GetAuthorLoginPage(isExec) {
  var loginSetInfo = wx.getStorageSync("LoginSet");
  var UserInfo = wx.getStorageSync("UserInfo");
  if (loginSetInfo && loginSetInfo.IsFollowTis == 0 && loginSetInfo.IsLogin == 1 && (!UserInfo || UserInfo.HasPwd == false)) {
    var LogPageArr = loginSetInfo.LoginSettPage.split(',');
    var returnUrl = getCurrentPageUrlWithArgs();
    var loginUrl = "/pages/login/login?wxHidd=hidden&pageUrl=" + encodeURIComponent(returnUrl)
    if (LogPageArr.indexOf("0") > -1) { //已进入页面的时候就调到登陆页
      wx.redirectTo({
        url: loginUrl,
      })
      return false;
    } else if (LogPageArr.indexOf("1") > -1 && (returnUrl.toLowerCase().indexOf("pages/details/details") > -1 || isExec == "123")) {
      //点击商品时也就是进入商品详情页
      wx.redirectTo({
        url: loginUrl,
      })
      return false;
    } else if (LogPageArr.indexOf("2") > -1 && (isExec == "123")) { //提交订单
      wx.redirectTo({
        url: loginUrl,
      })
      return false;
    } else if (LogPageArr.indexOf("3") > -1 && (returnUrl.toLowerCase().indexOf("/my/my") > -1 || isExec == "123")) //个人中心
    {
      wx.redirectTo({
        url: loginUrl,
      })
      return false;
    }
  }
  return true;
}
/**
 * 判断是否要绑定手机号码
 * 
 */
function GetLoginBindPhone(isExec) {
  var loginSetInfo = wx.getStorageSync("LoginSet");
  var UserInfo = wx.getStorageSync("UserInfo");
  if (loginSetInfo && loginSetInfo.IsBindMobile == 1 && UserInfo && !UserInfo.Phone) { //启动了登陆页
    var PhonePageArr = loginSetInfo.BindMobileSettPage.split(',');
    var returnUrl = getCurrentPageUrlWithArgs();
    var loginUrl = "/pages/register/register?pageUrl=" + encodeURIComponent(returnUrl);
    if (PhonePageArr.indexOf("0") > -1) { //已进入页面的时候就调到登陆页
      wx.redirectTo({
        url: loginUrl,
      })
      return false;
    } else if (PhonePageArr.indexOf("1") > -1 && (returnUrl.toLowerCase().indexOf("pages/details/details") > -1 || isExec == "123")) {
      //点击商品时也就是进入商品详情页
      wx.redirectTo({
        url: loginUrl,
      })
      return false;
    } else if (PhonePageArr.indexOf("2") > -1 && (isExec == "123")) { //点击提交订单按钮
      wx.redirectTo({
        url: loginUrl,
      })
      return false;
    } else if (PhonePageArr.indexOf("3") > -1 && (returnUrl.toLowerCase().indexOf("my/my") > -1 || isExec == "123")) //个人中心
    {
      wx.redirectTo({
        url: loginUrl,
      })
      return false;
    }
  }
  return true;
}



/**
 * 获取sessionKey, failCB
 */
function getSessionKey(successCB) {

  wx.login({
    success: function(resCode) {
      var app = getApp();
      var postData = null;
      var url = "";
      if (app.globalData.isAuthComponent) {
        url = app.globalData.apiurl + '/member/api/Small/ComponentJsCode2Json';
        postData = {
          zpAppId: app.globalData.zhengpinAppid,
          jsCode: resCode.code
        };
      } else {
        url = app.globalData.apiurl + '/member/api/Small/JsCode2Json';
        postData = {
          jsCode: resCode.code,
          appId: app.globalData.zpAppid,
          secret: app.globalData.secret,
          grant_type: 'authorization_code',
        }
      }
      wx.request({
        url: url,
        method: "get",
        data: postData,
        header: {
          'X_ManuName': app.globalData.manuName,
        },
        success: res => { //成功
          var data = res.data;

          if (res.statusCode == 200 && data.code == 1200 && data.content.session_key) {
            successCB(data.content.session_key);
          } else {
            wx.showModal({
              content: "请求getSessionKey出错!",
              showCancel: false,
              confirmText: "确定"
            })
            // failCB();
          }
        },
        fail: res => {
          wx.showModal({
            content: "网络请求getSessionKey失败!",
            showCancel: false,
            confirmText: "确定"
          })
          // failCB();
        }
      })
    },
    fail: res => {
      wx.showModal({
        content: "登陆失败",
        showCancel: false,
        confirmText: "确定"
      })
      // failCB();
    }
  })
}

function logShare(ProductID, Name, Img, Price, Commission, Link) {
  var app = getApp();
  var url = app.globalData.apiurl + '/mobile/api/ShareLog/Log';
  var postData = {
    CustID: app.globalData.custID,
    UserID: wx.getStorageSync('UserInfo').UserID,
    ProductID: ProductID,
    Name: Name,
    Img: Img,
    Price: Price,
    Commission: Commission,
    Link: Link

  }
  wx.request({
    url: url,
    method: "post",
    data: postData,
    header: {
      'X_ManuName': app.globalData.manuName,
    },
    success: res => { //成功

    },
    fail: res => {

    }
  })
}

module.exports = {
  pageInit: pageInit,
  wxRequest: wxRequest,
  navigateTo: navigateTo,
  switchTab: switchTab,
  redirectTo: redirectTo,
  getCurrentPageUrlWithArgs: getCurrentPageUrlWithArgs,
  GetLoginBindPhone: GetLoginBindPhone,
  GetAuthorLoginPage: GetAuthorLoginPage,
  getSessionKey: getSessionKey,
  logShare: logShare,
}